package com.kischang.blog.dao;

import com.kischang.blog.model.PageInfo;
import com.kischang.blog.model.Reply;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ReviewDao {
	@Autowired
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public List<Reply> getReviewByPageAndTopicID(int tid, PageInfo pageInfo) {
		Session session = sessionFactory.getCurrentSession();
		return session
				.createQuery(
						"FROM Review AS r WHERE r.topic=:tid ORDER BY r.id DESC")
				.setInteger("tid", tid)
				.setFirstResult(
						(pageInfo.getPageNow() - 1) * pageInfo.getPageSize())
				.setMaxResults(pageInfo.getPageSize()).list();
	}

	public int getReviewCountByTid(int tid) {
		Session session = sessionFactory.getCurrentSession();
		return ((Long) session
				.createQuery(
						"SELECT COUNT(r.id) FROM Review AS r WHERE r.topic=:tid")
				.setInteger("tid", tid).uniqueResult()).intValue();
	}
}
